/*
 * 魔妆镜后台登录页面
 * @Author: ljb
 * @Date: 2018-03-26 10:18:23
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-25 16:41:32
 */
<style lang="less" rel="stylesheet/less" type="text/less">
.v-admin-login-index {
	position: relative;
	padding-top: 20px;
    width: 100%;
    height: 100%;
    padding-top: 20px;
    background-image: url('//beauty-mirror.gz.bcebos.com/web_admin/login_bg1.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 0 0;
    background-color: #f0f2f5;
    color: #fff;
    .login-content {
		width: 1100px;
		height: 600px;
		padding-top: -20px;
		margin: 8% auto 0;
		border-radius: 10px;
		overflow: hidden;
		display: flex;
		justify-content: center;
		/*tabs选项卡切换*/
		.form-tabs {
			.ivu-tabs-tab {
				padding: 15px 20px;
				font-size: 16px;
			}
		}
		/*tabs选项卡切换 END*/
        .login-box {
			background: #fff;
            position: relative;
            width: 500px;
            height: 600px;
			padding: 20px 40px;
            h1 {
                line-height: 80px;
                text-align: center;
                letter-spacing: 3px;
                img {
                    width: 50%;
                }
            }
            .right {
				position: absolute;
				top: 370px;
				right: 75px;
				color: #2D8DF0;
				font-size: 14px;
                &:hover {
                    opacity: 0.8;
                }
			}
			.form-input {
				padding: 0 40px;
				margin: 70px 0;
				span {
					color: #B3D8FF;
					font-size: 12px;
					margin-left: 5px;
				}
				/*input输入框样式*/
				input {
					display: block;
					border: none;
					border-bottom: 1px solid #E5E5E5;
					width: 100%;
					outline: none;
					font-size: 14px;
					color: #333;
				}
			}
			/*表单按钮样式*/
			.form-button {
				text-align: center;
				.ivu-btn-primary {
					height: 45px;
					width: 350px;
					border-radius: 25px;
					font-size: 16px;
					color: #fff;
					margin-top: 50px;
					box-shadow: 0 9px 30px rgba(45,140,240,0.5);
				}
			}
			/*表单按钮样式 END*/
        }
    }
    .login-load {
        background-color: rgba(0, 0, 0, 0.5);
    }
    .footer-logo {
        position: absolute;
        bottom: 10px;
        width: 100%;
        height: 30px;
        font-size: 0;
        text-align: center;
        img {
            height: 100%;
        }
	}
	.language{
		position: absolute;
		right: 40px;
	}
}
</style>
<template>
	<div
		:class="{'admin-background': form_data.type === 'panx',
			'customer-background': form_data.type === 'customer',
			'store-background': form_data.type === 'store',
		}"
		class="v-admin-login-index">

		<!-- BEGIN: 切换语言 -->
		<Dropdown
			class="drop-down language"
			trigger="click"
			placement="bottom-end"
			@on-click="changLanguage">

			<Button type="default">
				<Icon type="ios-world-outline" /> {{ getCurrentLanguage }}
				<Icon type="arrow-down-b"/>
			</Button>

			<Dropdown-menu slot="list">
				<Dropdown-item
					v-for="(language, locale) in getLanguageOptions"
					:key="locale"
					:name="locale">{{ language }}</Dropdown-item>
			</Dropdown-menu>
		</Dropdown>
		<!-- END: 切换语言 -->

		<div class="login-content _fun-hide">
			<div>
				<img
					src="//beauty-mirror.gz.bcebos.com/web_admin/login_bg2.jpg"
					alt="">
			</div>
			<div
				v-show="forgotPass_show"
				class="login-box">
				<Form
					ref="formData"
					:model="form_data"
					:rules="ruleInline">

					<Tabs
						class="form-tabs"
						value="panx"
						@on-click="changeTab">
						<TabPane
							:label="$t('login.panx_login')"
							class="panx-login"
							name="panx">
							<Form-item
								prop="user"
								class="form-input">
								<span>{{ $t('login.panx_account') }}</span>
								<input
									v-model="form_data.user"
									:placeholder="$t('login.please_enter_account')"
									type="text"
									name="panx-user"
								>
							</Form-item>
							<Form-item
								prop="password"
								class="form-input">
								<span>{{ $t('login.panx_password') }}</span>
								<input
									v-model="form_data.password"
									:placeholder="$t('login.please_enter_password')"
									type="password"
									name="panx-password"
									@keydown.enter="handleSubmit('formData')">
							</Form-item>
						</TabPane>
						<TabPane
							:label="$t('login.cust_login')"
							class="customer-login"
							name="customer">
							<Form-item
								prop="user"
								class="form-input">
								<span>{{ $t('login.cust_account') }}</span>
								<input
									v-model="form_data.user"
									:placeholder="$t('login.please_enter_account')"
									type="text"
									name="customer-user">
							</Form-item>
							<Form-item
								prop="password"
								class="form-input">
								<span>{{ $t('login.cust_password') }}</span>
								<input
									v-model="form_data.password"
									:placeholder="$t('login.please_enter_password')"
									type="password"
									name="customer-password"
									@keydown.enter="handleSubmit('formData')">
							</Form-item>
						</TabPane>
						<TabPane
							:label="$t('login.store_login')"
							class="store-login"
							name="store">
							<Form-item
								prop="user"
								class="form-input">
								<span>{{ $t('login.store_account') }}</span>
								<input
									v-model="form_data.user"
									:placeholder="$t('login.please_enter_account')"
									type="text"
									name="store-user">
							</Form-item>
							<Form-item
								prop="password"
								class="form-input">
								<span>{{ $t('login.store_password') }}</span>
								<input
									v-model="form_data.password"
									:placeholder="$t('login.please_enter_password')"
									type="password"
									name="store-password"
									@keydown.enter="handleSubmit('formData')">
							</Form-item>
						</TabPane>
					</Tabs>

					<a
						href="#"
						class="right"
						@click.prevent="goForgetPass">
						{{ $t('login.is_forget') }}
					</a>
					<Form-item
						class="form-button">
						<Button
							type="primary"
							long
							@click="handleSubmit('formData')">
							{{ $t('login.login') }}
						</Button>
					</Form-item>
				</Form>

				<Spin
					v-if="login_loading"
					fix
					class="login-load">
					<Icon
						type="load-c"
						size="18"
						class="demo-spin-icon-load" />
					<div>
						{{ $t('login.please_wait') }}
					</div>
				</Spin>
			</div>
			<!-- 忘记密码 -->
			<div
				v-if="!forgotPass_show">
				<forgot-password
					:email-show="email_show"
					:asterisk-email="asterisk_email"
					:loading="login_loading"
					@senEmail="forgetPassword"
					@loginShow="loginShow"
					@backUp="backUp"/>
			</div>
		</div>
		<!-- 底部logo -->
		<div class="footer-logo">
			<img
				src="//beauty-mirror.gz.bcebos.com/web_admin%2Fpanx_home_name.png"
				alt="">
		</div>
	</div>
</template>
<script type="text/babel">
import { mapActions, mapMutations, mapGetters } from 'vuex';
/* eslint-disable import/extensions */
import API_LIST from 'src/API_LIST.js';
// import { imgPreLoad } from 'src/utils/utils.js';
import { setCookie } from 'src/cookies.js';
import { getLanguage, getLanguageForBackEnd } from 'src/i18n';
import forgotPassword from './forgot-password';
/* eslint-endisable import/extensions */
export default {
	components: {
		forgotPassword,
	},
	data() {
		return {
			login_loading: false, // 登陆中

			forgotPass_show: true, // 忘记密码显隐
			email_show: true, // 邮箱验证显隐
			asterisk_email: '', // 带星星电子邮箱

			form_data: {
				user: '', // 用户名
				password: '', // 密码
				type: '', // 登录类型
				remember: false, // 是否记住密码
				language: getLanguageForBackEnd(),
			},

			img_arrs: [], // 预加载的图片数组

			ruleInline: {
				user: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('login.account') }),
						trigger: 'blur,change',
					},
				],
				password: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('login.password') }),
						trigger: 'blur,change',
					},
					{
						type: 'string',
						min: 6,
						message: this.$t('validate.min', { length: 6, field: this.$t('login.password') }),
						trigger: 'blur,change',
					},
				],
			},
		};
	},
	computed: {
		...mapGetters('app', [
			'getCurrentLanguage',
			'getLanguageOptions',
		]),
	},
	mounted() {
		this.form_data.type = 'panx';
	},
	methods: {
		// action的引用

		...mapActions('userToken', ['toSetToken', 'toSetUserInfo', 'toSetUserRoles', 'toSetUserType', 'toSetLoginPath', 'toSetProviderType', 'toSetYouzanAuthorize']),
		// ...mapActions('menu', ['resolveMenusAction']),

		...mapMutations('menu', ['setMenus', 'clearCache']),

		...mapMutations('app', [
			'setLocale',
		]),

		/**
		 * 控制登录页面显示
		 * @return {undefined} {description}
		 */
		goForgetPass() {
			this.email_show = true;
			this.forgotPass_show = false;
		},

		/**
		 * 返回上一级
		 * @return {undefined} {description}
		 */
		backUp() {
			this.email_show = true;
		},

		/**
		 * 控制登录页面显示
		 * @return {undefined} {description}
		 */
		loginShow() {
			this.forgotPass_show = true;
		},

		/**
         * 忘记密码
		 * @param {String} value {邮箱名称}
         * @return {undefined}
         */
		forgetPassword(value) {
			const param = {
				account: value,

				type: this.form_data.type,

				language: this.form_data.language,
			};

			this.login_loading = true;

			this.$http
				.post(API_LIST.FORGET_PASSWORD, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) { throw new Error(data.error); }

					this.$Message.success(this.$t('login.reset_success_tip'));

					this.email_show = false;
					this.asterisk_email = data.asterisk_email; // 带星星电子邮箱

					this.$Message.info({
						content: this.$t('login.warm_tip'),
						// '温馨提示！重置密码的邮件有可能存放于您邮箱的垃圾箱之中',
						duration: 10,
						closable: true,
					});
				})
				.catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText || this.$t('common.network_exception'),
						duration: 5,
						closable: true,
					});
				})
				.finally(() => {
					this.login_loading = false;
				});
		},

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			this.form_data.type = tab_name;
			this.handleReset('formData');
		},

		/**
         * 重置表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleReset(name) {
			this.$refs[name].resetFields();
		},

		// 提交表单的方法
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.login_loading = true;

					if (this.form_data.remember) {
						setCookie('user', this.form_data.user, 7); // 保存帐号到cookie，有效期7天
						setCookie('pswd', this.form_data.password, 7); // 保存密码到cookie，有效期7天
					}

					this.loginRequest(API_LIST.ADMIN_LOGIN);
				} else {
					this.$Message.error(this.$t('login.reset_psw_error_tip'));
				}
			});
		},

		/**
         * @function {function loginRequest}登录
         * @param  {string=} url  {请求api的网址}
         * @return {undefined}
         */
		loginRequest(url) {
			this.toSetUserType(this.form_data.type);

			const self = this;

			let params = {};

			const lang = getLanguage();

			if (window.DEBUG) {
				params = {
					account: self.form_data.user,
					password: self.form_data.password,
					type: self.form_data.type,
					debug: window.DEBUG,
					lang,
				};
			} else {
				params = {
					account: self.form_data.user,
					password: self.form_data.password,
					type: self.form_data.type,
					lang,
				};
			}

			this.clearCache();

			this.setMenus(this.form_data.type);
			// this.resolveMenusAction();

			this.$http
				.post(url, params, {
					headers: { 'Accept-Language': getLanguage() },
				})
				.then(({ data }) => {
					if (parseInt(data.code, 10) === 0) {
						this.login_loading = false;

						this.toSetToken(data.token);

						this.toSetUserInfo(data.admin);

						this.toSetYouzanAuthorize(data.admin.has_youzan_authorize); // 保存有赞授权

						this.toSetUserRoles(data.roles); // 保存角色

						this.toSetLoginPath(this.$route.path);// 保存登陆进去的网址

						this.$Message.success(this.$t('login.login_success'));

						this.jumpToHomePage();
					} else {
						throw new Error(data.error);
					}
				})
				.catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});

					this.login_loading = false;
				});
		},

		/**
         *  登陆后，转跳到首页
         */
		jumpToHomePage() {
			switch (this.form_data.type) {
			case 'panx':

				this.$router.push({
					path: '/admin/',
				});

				break;
			case 'customer':

				this.$router.push({
					path: '/customer/',
				});

				break;

			default:
				this.$router.push({
					path: '/store/',
				});

				break;
			}
		},

		/**
		 *  切换语言
		 */
		changLanguage(language) {
			this.setLocale(language);
		},
	},
};
</script>
